package com.vr.cloudpicture.manager.websocket.strategy.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import com.vr.cloudpicture.manager.websocket.handler.PictureEditBroadcast;
import com.vr.cloudpicture.manager.websocket.handler.PictureEditingStatusManager;
import com.vr.cloudpicture.manager.websocket.model.PictureEditRequestMessage;
import com.vr.cloudpicture.manager.websocket.model.PictureEditResponseMessage;
import com.vr.cloudpicture.manager.websocket.model.enums.PictureEditActionEnum;
import com.vr.cloudpicture.manager.websocket.model.enums.PictureEditMessageTypeEnum;
import com.vr.cloudpicture.manager.websocket.strategy.PictureEditMessageStrategy;
import com.vr.cloudpicture.model.dto.user.UserLogin;
import com.vr.cloudpicture.model.vo.UserVO;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

/**
 * 执行编辑操作状态的策略
 *
 * @author hzh
 * @date 2025/05/28
 */
@Component
public class EditActionMessageStrategy implements PictureEditMessageStrategy {
    @Override
    public void handle(PictureEditRequestMessage requestMessage, WebSocketSession session, UserLogin user, Long pictureId) throws Exception {
        // 用户执行编辑操作时应该将操作同步到处自己外一张图片的其他客户端
        Long editingUser = PictureEditingStatusManager.getEditingUser(pictureId);
        String editAction = requestMessage.getEditAction();
        PictureEditActionEnum editActionEnum = PictureEditActionEnum.getEnumByValue(editAction);
        // 为null时，表示编辑行为不合法或者为空
        if (editActionEnum==null) {
            return;
        }
        // 确认当前登录的用户是否是当前编辑图片的人
        if (ObjUtil.isNotEmpty(editingUser) && user.getId().equals(editingUser)) {
            // 确认是当前编辑者
            // 构建响应
            PictureEditResponseMessage responseMessage = new PictureEditResponseMessage();
            responseMessage.setType(PictureEditMessageTypeEnum.EDIT_ACTION.getValue());
            responseMessage.setEditAction(editAction);
            String message = String.format("%s执行%s", user.getUserName(), editActionEnum.getText());
            responseMessage.setMessage(message);
            responseMessage.setUser(BeanUtil.toBean(user, UserVO.class));
            // 广播通知给同一张图片的所有用户,除自己外，否则会出现重复编辑
            PictureEditBroadcast.broadcastToPicture(pictureId, responseMessage,session);
        }
    }
}
